package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @create: 2024/8/29
 * @author: gyhe10
 * @description:
 **/

@Controller
public class IndexController {

    @Resource
    private CategoryService categoryService;
    @Resource
    private RedissonClient redissonClient;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {
        long start = System.currentTimeMillis();
        // 查询所有的商品一级分类
        List<CategoryEntity> list = categoryService.getLevelOneCategories();
        // System.out.println("查询一级分类耗时：" + (System.currentTimeMillis() - start));
        // 封装到 model 中
        model.addAttribute("categories", list);

        // 默认前缀：classpath:/templates/
        // 默认后缀：.html
        // 视图解析器拼接完整的路径：classpath:/templates/逻辑视图.html
        // 返回值就是视图名称，也叫逻辑视图，会被视图解析器处理
        return "index";
    }

    /**
     * 获取商品二级三级分类数据，响应为 JSON 格式
     * @return
     */
    @ResponseBody// 返回 JSON 格式数据
    @GetMapping("/index/json/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        return categoryService.getCatalogJson();
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        // 获取分布式锁
        RLock myLock = redissonClient.getLock("myLock");
        // 加锁
        myLock.lock();
        String result = "";
        try {
            // 业务逻辑
            System.out.println("加锁成功，执行业务逻辑..." + Thread.currentThread().getId());
            Thread.sleep(20000);
            result = "world";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            System.out.println("释放锁..." + Thread.currentThread().getId());
            myLock.unlock();
        }
        return result;


    }
}
